import logging
from typing import Tuple
import requests
from configs import app_config
from libs.hmac_header import get_hmac_header


class IntentRemoteService:
    """
    调取Dify创建意图识别i知识库和
    Document
    """
    

    CREATE_GROUP_ENDPOINT = "/intent/group"
    @classmethod
    def create_group_doc(cls,group_name: str,dataset_id:str|None,collection_name:str|None) -> Tuple[str|None, str|None,str|None,str]:
        base_url = app_config.REMOTE_ROBOT_SERVER_HOST.rstrip('/')
        endpoint = cls.CREATE_GROUP_ENDPOINT
        
        url = f"{base_url}/{endpoint.lstrip('/')}"
        
        try:
            data= {
                "group_name":group_name,
                "dataset_id":str(dataset_id) if dataset_id else None,
                "collection_name":collection_name if collection_name else None,
            }
            response = requests.post(url,json=data,headers=get_hmac_header(), timeout=5)  # 设置5秒超时
            response.raise_for_status()  # 如果状态码不是2xx，抛出异常
            
            data = response.json()
            if data.get("code") == 200:
                dataset_id = data.get("dataset_id",None)
                document_id = data.get("document_id",None)
                document_name = data.get("document_name",None)
                return dataset_id,document_id,document_name,"SUCCESS"
            return None,None,None,data.get("message","Unknown Error")
        
        except requests.exceptions.RequestException as e:
            logging.error(f"CREATE_GROUP_DOC:Request failed for dataset_id {dataset_id}: {e}", exc_info=False)
            return None,None,None,str(e)
        except Exception as e:
            logging.error(f"CREATE_GROUP_DOC:Request failed for dataset_id {dataset_id}: {e}", exc_info=False)
            return None,None,None,str(e)
        
    LINK_INTENT_GROUP_ENDPOINT = "/robots/intent/group/link"
    @classmethod
    def link_terms_to_group(cls,dataset_id: str,document_id:str,func_terms:dict)->dict:
        """
        code=200
        message=Task created
        """
        base_url = app_config.REMOTE_ROBOT_SERVER_HOST.rstrip('/')
        endpoint = cls.LINK_INTENT_GROUP_ENDPOINT
        
        url = f"{base_url}/{endpoint.lstrip('/')}"
        
        try:
            data={
                "dataset_id":dataset_id,
                "document_id":document_id,
                "func_terms":func_terms
            }
            response = requests.post(url,json=data,headers=get_hmac_header(), timeout=5)  # 设置5秒超时
            response.raise_for_status()  # 如果状态码不是2xx，抛出异常
            
            data = response.json()
            return data
        except requests.exceptions.RequestException as e:
            logging.error(f"link_terms_to_group:Request failed for document_id {document_id}: {e}", exc_info=False)
            return {"code": 500, "message": f"请求失败{str(e)}"}
        
    @classmethod
    def link_terms_to_group_task_status(cls,dataset_id: str,document_id:str,)->dict:
        base_url = app_config.REMOTE_ROBOT_SERVER_HOST.rstrip('/')
        endpoint = cls.LINK_INTENT_GROUP_ENDPOINT
        
        url = f"{base_url}/{endpoint.lstrip('/')}"
        
        try:
            data= {
                "dataset_id": dataset_id,
                "document_id": document_id,
            }
            response = requests.post(url,params=data,headers=get_hmac_header(), timeout=2)  # 设置5秒超时
            response.raise_for_status()  # 如果状态码不是2xx，抛出异常
            
            data = response.json()
            return data
        
        except requests.exceptions.RequestException as e:
            logging.error(f"link_terms_to_group_task_state:Request failed for dataset_id {dataset_id}: {e}", exc_info=False)
            return {
                "status": "request status failed",
                "message": str(e),
            }
        except Exception as e:
            logging.error(f"link_terms_to_group_task_status:Request failed for dataset_id {dataset_id}: {e}", exc_info=False)
            return {
                "status": "request status failed",
                "message": str(e),
            }
